<template>
  <div class="cpu-meter-container demo-spin-col">
    <p class="cpu-meter-title">终端CPU使用率</p>
    <div class="cpu-meter-box" v-for="item of cpuArr">
      <Meter :titleTxt="item.title" :min="item.min" :max="item.max" :percentage="item.percent"></Meter>
    </div>
    <Spin fix v-if="loadingShow">
      <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      <div>Loading</div>
    </Spin>
  </div>
</template>
<script>
import Meter from "./meter";
import axios from "axios";
import $ from "jquery";
export default {
  components: {
    Meter
  },
  props:['ipArr'],
  mounted() {
    this.getCpuMaxMin();
    this.timer=setInterval(()=>{
      for(let item of this.ipArr){
        this.getEveryData(item.hostid,item.ip)
      }
    },60000)
  },
  destroyed () {
    clearInterval(this.timer);
  },
  watch:{
    //监听双向绑定数据变化  调用handleOn方法  存入localStorage 做到双向绑定
    ipArr:{
      handler:function(val, oldVal) {
        this.ipArr=val
        this.getWindowInfo();
      },
      deep:true
    }
  },
  data() {
    return {
      cpuArr: [],
      // hostIdArr:[],
      max:0,
      min:0,
      timer:null,
      // ipArr:[]
      loadingShow:true
    };
  },
  methods: {
    // 获取服务端为window的hostid
    // getWindowInfo() {
    //   var _this = this;
    //   var data = {
    //     jsonrpc: "2.0",
    //     method: "host.get",
    //     params: {
    //       output: ["hostid"],
    //       selectGroups: "extend",
    //       filter: {
    //         host: []
    //       }
    //     },
    //     auth: localStorage.getItem("auth"),
    //     id: localStorage.getItem("currentId")
    //   };
    //   this.$http.post("/zabbix/api_jsonrpc.php", data).then(
    //     res => {
    //       if (res.result) {
    //         _this.hostIdArr=[]
    //         res.result.forEach((v, index) => {
    //           if (v.groups[0].name == "windows") {
    //           // if (v.groups[0].name == "Linux servers") {
    //             _this.hostIdArr = _this.hostIdArr.concat(v.hostid);
    //           }
    //         });
    //         _this.getServerInfo()
    //       }
    //     },
    //     err => {
    //       console.log(err);
    //     }
    //   );
    // },
    // // 获取该hostid对应的东西
    // getServerInfo() {
    //   var _this = this;
    //   var data = {
    //     jsonrpc: "2.0",
    //     method: "host.get",
    //     params: {
    //       output: ["hostid", "host"],
    //       selectInterfaces: ["interfaceid", "ip"]
    //     },
    //     auth: localStorage.getItem("auth"),
    //     id: localStorage.getItem("currentId")
    //   };
    //   this.$http.post("/zabbix/api_jsonrpc.php", data).then(
    //     res => {
    //       if (res.result) {
    //         _this.cpuArr=[]
    //         res.result.forEach((v, index) => {
    //           for(let item of _this.hostIdArr){
    //             if (v.hostid == item) {
    //               _this.getTerminalCpu(v.hostid,v.interfaces[0].ip)
    //               _this.ipArr.push({
    //                 hostid:v.hostid,
    //                 ip:v.interfaces[0].ip
    //               })
    //             }
    //           }
    //         });
    //       }
    //     },
    //     err => {
    //       console.log(err);
    //     }
    //   );
    // },
    getWindowInfo(){
      for(let item of this.ipArr){
        this.getTerminalCpu(item.hostid,item.ip)
      }
    },
    // 获取CPU权重值
    getCpuMaxMin(){
      var _this = this;
      var obj = {
        type: 'cpu_min_max'
      };
      obj=JSON.stringify(obj)
      $.ajax({
        url:'http://192.168.96.9:9080/api/global_config',
        type:"post",
        contentType:"application/json",
        Connection: "Keep-Alive",
        KeepAlive: "timeout=60",
        dataType:"json",
        data:obj,
        timeout:60000,
        success:(res)=>{
          _this.max=Number(res.info.max.replace(/%/, ""));
          _this.min=Number(res.info.min.replace(/%/, ""));
        },
        error:(err)=>{
          console.log(err)
        }
      })
    },
    //获取终端CPU
    getTerminalCpu(hostid,title){
      var _this=this;
      var data={
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "extend",
            "hostids": hostid,
            "search": {
              "key_": "system.cpu"
            },
            "sortfield": "name"
        },
        "auth": localStorage.getItem('auth'),
        "id": 1
      }
      this.$http.post('/zabbix/api_jsonrpc.php',data).then(
        res=>{
          if(res.result.length!=0){
            let value=0;
            let a=0;
            res.result.forEach((item,index )=> {
              if(item.key_.indexOf("system.cpu.load[") != -1){
                value+=Number(item.lastvalue)
                a++;
              }
            });
            _this.cpuArr.push({
              hostid: hostid,
              title: title,
              min:_this.min,
              max:_this.max,
              percent:Math.round(value/a)
            })
          }
          if(res.result.length==0){
            _this.cpuArr.push({
              hostid: hostid,
              title: title,
              min:_this.min,
              max:_this.max,
              percent:0
            })
          }
          _this.shiftData();
          this.loadingShow=false;
        },
        err=>{
          console.log(err);
        }
      )
    },
    //获取实时数据
    getEveryData(hostid,title){
      var _this=this;
      var data={
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "extend",
            "hostids": hostid,
            "search": {
              "key_": "system.cpu"
            },
            "sortfield": "name"
        },
        "auth": localStorage.getItem('auth'),
        "id": 1
      }
      this.$http.post('/zabbix/api_jsonrpc.php',data).then(
        res=>{
          if(res.result.length!=0){
            let value=0;
            let a=0;
            res.result.forEach((item,index )=> {
              if(item.key_.indexOf("system.cpu.load[") != -1){
                value+=Number(item.lastvalue)
                a++;
              }
            });
            _this.cpuArr.forEach((item,index )=> {
              if(item.hostid==hostid){
                item.percent=Math.round(value/a)
              }
            });
          }
          if(res.result.length==0){
            _this.cpuArr.forEach((item,index )=> {
              if(item.hostid==hostid){
                item.percent=0
              }
            });
          }
        },
        err=>{
          console.log(err);
        }
      )
    },
    // 筛选数据
    shiftData(){
      this.cpuArr.sort((a,b)=>{
        return -(a.percent-b.percent)
      })
      if(this.cpuArr.length>10){
        this.cpuArr=this.cpuArr.slice(0,10)
      }
    }
  }
};
</script>

<style scoped>
.cpu-meter-container {
  display: inline-block;
  width: 600px;
  height: 220px;
  border: 28px solid;
  border-top: 5px solid;
  border-left: 5px solid;
  background: transparent;
  border-image: url("../assets/images/13.png") 28 fill repeat;
}
.cpu-meter-title {
  color: #fff;
  font-size: 16px;
  /* font-weight: bold; */
}
.cpu-meter-box {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  display: inline-block;
  margin-right: 8px;
}
/*加载中的作用范围*/
.demo-spin-col{
  position: relative;
}
.ivu-spin-fix{
  background-color: rgba(0, 0, 0, .2);
}
.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
</style>
